package edu.jmu.transmissionassistant.component

import com.yanzhenjie.andserver.annotation.Resolver
import com.yanzhenjie.andserver.error.HttpException
import com.yanzhenjie.andserver.framework.ExceptionResolver
import com.yanzhenjie.andserver.framework.body.JsonBody
import com.yanzhenjie.andserver.http.HttpRequest
import com.yanzhenjie.andserver.http.HttpResponse
import com.yanzhenjie.andserver.http.StatusCode
import edu.jmu.transmissionassistant.model.ReturnData
import edu.jmu.transmissionassistant.util.JsonUtils


/**
 * TODO 统一异常处理
 */
@Resolver
class AppExceptionResolver : ExceptionResolver {
    override fun onResolve(request: HttpRequest, response: HttpResponse, e: Throwable) {
        if (e is HttpException) {
            response.status = e.statusCode
        } else {
            response.status = StatusCode.SC_INTERNAL_SERVER_ERROR
        }
        val returned = ReturnData()
        returned.isSuccess = false
        returned.errorMsg = e.message
        val jsonString = JsonUtils.toJsonString(returned)
        response.setBody(JsonBody(jsonString))
    }
}